package com.unit.dbutils.processor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;

import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.ColumnHandler;

import com.unit.dbutils.handler.EnumGeneralHandler;
import com.unit.dbutils.handler.TimeGeneralHandler;

public class GeneraBeanProcessor extends BeanProcessor {

	private static ServiceLoader<ColumnHandler> columnHandlers = ServiceLoader.load(ColumnHandler.class);

	private static List<ColumnHandler> customList = new ArrayList<>();

	static {
		customList.add(new TimeGeneralHandler());
		customList.add(new EnumGeneralHandler());
	}

	public GeneraBeanProcessor(Map<String, String> columnToPropertyMap) {
		super(columnToPropertyMap);
	}

	@Override
	protected Object processColumn(ResultSet rs, int index, Class<?> propType) throws SQLException {
		Object retval = rs.getObject(index);
		if (!propType.isPrimitive() && retval == null) {
			return null;
		}
		
		boolean flag = true;
		
		for (ColumnHandler handler : columnHandlers) {
			if (handler.match(propType)) {
				retval = handler.apply(rs, index);
				flag = false;
				break;
			}
		}

		if(flag) {
			for (ColumnHandler handler : customList) {
				if (handler.match(propType)) {
					retval = handler.apply(rs, index);
					break;
				}
			}
		}
		return retval;
	}
}
